<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>交易管理 - 银行业务管理系统</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        
        .navbar-brand {
            font-weight: bold;
            color: #007bff !important;
        }
        
        .sidebar {
            min-height: calc(100vh - 56px);
            background-color: #343a40;
            padding-top: 20px;
        }
        
        .sidebar .nav-link {
            color: #adb5bd;
            padding: 10px 20px;
            border-radius: 0;
        }
        
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: #fff;
            background-color: #495057;
        }
        
        .main-content {
            padding: 20px;
        }
        
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
            margin-bottom: 20px;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid rgba(0, 0, 0, 0.125);
            font-weight: 600;
        }
        
        .table th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .search-form {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .modal-header {
            background-color: #007bff;
            color: white;
        }
        
        .money-amount {
            font-weight: bold;
            color: #28a745;
        }
        
        .trade-type-deposit {
            color: #28a745;
            font-weight: bold;
        }
        
        .trade-type-withdraw {
            color: #dc3545;
            font-weight: bold;
        }
        
        .trade-type-transfer {
            color: #007bff;
            font-weight: bold;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .stats-number {
            font-size: 1.5rem;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin">
                <i class="fas fa-university"></i>
                银行业务管理系统 - 管理员
            </a>
            
            <div class="navbar-nav ml-auto">
                <a class="nav-link" href="/">
                    <i class="fas fa-home"></i> 返回首页
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-none d-md-block sidebar">
                <div class="sidebar-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/admin">
                                <i class="fas fa-university"></i> 快捷操作
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/customers">
                                <i class="fas fa-users"></i> 客户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/cards">
                                <i class="fas fa-credit-card"></i> 银行卡管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/deposit-types">
                                <i class="fas fa-piggy-bank"></i> 存款业务管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/admin/trades">
                                <i class="fas fa-exchange-alt"></i> 交易管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-toggle="collapse" data-target="#viewsSubmenu" aria-expanded="true">
                                <i class="fas fa-eye"></i> 视图查询 <i class="fas fa-caret-down"></i>
                            </a>
                            <div class="collapse show" id="viewsSubmenu">
                                <ul class="nav flex-column ml-3">
                                    <li class="nav-item">
                                        <a class="nav-link" href="/admin/views/customer-cards">
                                            <i class="fas fa-credit-card"></i> 客户银行卡视图
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/admin/views/trade-details">
                                            <i class="fas fa-list-alt"></i> 交易明细视图
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-10 ml-sm-auto main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-exchange-alt"></i> 交易管理
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group mr-2">
                            <button type="button" class="btn btn-success" onclick="exportTrades()">
                                <i class="fas fa-download"></i> 导出交易记录
                            </button>
                            <button type="button" class="btn btn-info" onclick="exportStatistics()">
                                <i class="fas fa-chart-bar"></i> 导出统计报表
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="refreshTable()">
                                <i class="fas fa-sync-alt"></i> 刷新
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div class="row" id="statisticsCards">
                    <!-- 统计卡片将通过JavaScript动态生成 -->
                </div>

                <!-- 搜索表单 -->
                <div class="search-form">
                    <form id="searchForm">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchCardId">银行卡号</label>
                                    <input type="text" class="form-control" id="searchCardId" placeholder="精确查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchCustomerName">客户姓名</label>
                                    <input type="text" class="form-control" id="searchCustomerName" placeholder="支持模糊查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchTradeType">交易类型</label>
                                    <select class="form-control" id="searchTradeType">
                                        <option value="">全部类型</option>
                                        <option value="存入">存入</option>
                                        <option value="支取">支取</option>
                                        <option value="转账">转账</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <div>
                                        <button type="button" class="btn btn-primary" onclick="searchTrades()">
                                            <i class="fas fa-search"></i> 查询
                                        </button>
                                        <button type="button" class="btn btn-secondary ml-2" onclick="resetSearch()">
                                            <i class="fas fa-undo"></i> 重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchStartTime">交易开始时间</label>
                                    <input type="datetime-local" class="form-control" id="searchStartTime">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchEndTime">交易结束时间</label>
                                    <input type="datetime-local" class="form-control" id="searchEndTime">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchMinAmount">最小金额</label>
                                    <input type="number" class="form-control" id="searchMinAmount" step="0.01" min="0" placeholder="0.00">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchMaxAmount">最大金额</label>
                                    <input type="number" class="form-control" id="searchMaxAmount" step="0.01" min="0" placeholder="不限">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 数据表格 -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-table"></i> 交易记录列表
                        <span class="badge badge-primary ml-2" id="totalCount">0</span>
                    </div>
                    <div class="card-body">
                        <div class="loading">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载数据...</p>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover" id="tradeTable">
                                <thead>
                                    <tr>
                                        <th>交易ID</th>
                                        <th>银行卡号</th>
                                        <th>客户姓名</th>
                                        <th>交易类型</th>
                                        <th>交易金额</th>
                                        <th>目标卡号</th>
                                        <th>交易时间</th>
                                        <th>备注</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="tradeTableBody">
                                    <!-- 数据将通过Ajax加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;

        // 页面加载完成后初始化
        $(document).ready(function() {
            loadTrades();
            loadStatistics();
        });

        // 加载交易数据
        function loadTrades(page = 1) {
            currentPage = page;
            showLoading(true);

            const searchParams = getSearchParams();
            const params = {
                current: currentPage,
                size: pageSize,
                ...searchParams
            };

            $.get('/admin/trades/page', params)
                .done(function(result) {
                    if (result.code === 200) {
                        renderTable(result.data);
                        renderPagination(result.data);
                        $('#totalCount').text(result.data.total);
                    } else {
                        showError('加载数据失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败，请检查网络连接');
                })
                .always(function() {
                    showLoading(false);
                });
        }

        // 加载统计数据
        function loadStatistics() {
            const searchParams = getSearchParams();
            const params = {};
            if (searchParams.startTime) params.startTime = searchParams.startTime;
            if (searchParams.endTime) params.endTime = searchParams.endTime;

            $.get('/admin/trades/statistics', params)
                .done(function(result) {
                    if (result.code === 200) {
                        renderStatistics(result.data);
                    }
                })
                .fail(function() {
                    console.log('统计数据加载失败');
                });
        }

        // 渲染统计卡片
        function renderStatistics(statistics) {
            const container = $('#statisticsCards');
            container.empty();

            if (statistics && statistics.length > 0) {
                const stats = statistics[0];

                const cards = [
                    {
                        title: '总交易数',
                        value: stats.totalCount || 0,
                        icon: 'fas fa-exchange-alt',
                        color: 'primary'
                    },
                    {
                        title: '存入笔数',
                        value: stats.depositCount || 0,
                        icon: 'fas fa-arrow-down',
                        color: 'success'
                    },
                    {
                        title: '支取笔数',
                        value: stats.withdrawCount || 0,
                        icon: 'fas fa-arrow-up',
                        color: 'danger'
                    },
                    {
                        title: '转账笔数',
                        value: stats.transferCount || 0,
                        icon: 'fas fa-exchange-alt',
                        color: 'info'
                    }
                ];

                cards.forEach(card => {
                    const cardHtml = `
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <div class="stats-number">${card.value}</div>
                                        <div>${card.title}</div>
                                    </div>
                                    <div>
                                        <i class="${card.icon} fa-2x" style="opacity: 0.3;"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    container.append(cardHtml);
                });
            }
        }

        // 获取搜索参数
        function getSearchParams() {
            return {
                cardId: $('#searchCardId').val().trim(),
                customerName: $('#searchCustomerName').val().trim(),
                tradeType: $('#searchTradeType').val(),
                startTime: $('#searchStartTime').val(),
                endTime: $('#searchEndTime').val(),
                minAmount: $('#searchMinAmount').val(),
                maxAmount: $('#searchMaxAmount').val()
            };
        }

        // 渲染表格
        function renderTable(pageData) {
            const tbody = $('#tradeTableBody');
            tbody.empty();

            if (pageData.records.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="9" class="text-center text-muted">
                            <i class="fas fa-inbox fa-2x mb-2"></i><br>
                            暂无数据
                        </td>
                    </tr>
                `);
                return;
            }

            pageData.records.forEach(trade => {
                const customerName = trade.cardInfo && trade.cardInfo.userInfo ?
                    trade.cardInfo.userInfo.customerName : '-';

                let tradeTypeClass = '';
                switch(trade.tradeType) {
                    case '存入':
                        tradeTypeClass = 'trade-type-deposit';
                        break;
                    case '支取':
                        tradeTypeClass = 'trade-type-withdraw';
                        break;
                    case '转账':
                        tradeTypeClass = 'trade-type-transfer';
                        break;
                }

                const row = `
                    <tr>
                        <td>${trade.tradeId}</td>
                        <td><code>${trade.cardId}</code></td>
                        <td>${customerName}</td>
                        <td><span class="${tradeTypeClass}">${trade.tradeType}</span></td>
                        <td class="money-amount">¥${formatMoney(trade.tradeMoney)}</td>
                        <td>${trade.targetCardId ? '<code>' + trade.targetCardId + '</code>' : '-'}</td>
                        <td>${formatDateTime(trade.tradeDate)}</td>
                        <td>${trade.remark || '-'}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-info" onclick="viewTrade(${trade.tradeId})">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                            <button class="btn btn-sm btn-outline-danger ml-1" onclick="deleteTrade(${trade.tradeId})">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 渲染分页
        function renderPagination(pageData) {
            const pagination = $('#pagination');
            pagination.empty();

            totalPages = pageData.pages;

            if (totalPages <= 1) return;

            // 上一页
            const prevDisabled = currentPage === 1 ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" onclick="loadTrades(${currentPage - 1})">上一页</a>
                </li>
            `);

            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const active = i === currentPage ? 'active' : '';
                pagination.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" onclick="loadTrades(${i})">${i}</a>
                    </li>
                `);
            }

            // 下一页
            const nextDisabled = currentPage === totalPages ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" onclick="loadTrades(${currentPage + 1})">下一页</a>
                </li>
            `);
        }

        // 显示/隐藏加载动画
        function showLoading(show) {
            if (show) {
                $('.loading').show();
                $('#tradeTable').hide();
            } else {
                $('.loading').hide();
                $('#tradeTable').show();
            }
        }

        // 搜索交易记录
        function searchTrades() {
            loadTrades(1);
            loadStatistics();
        }

        // 重置搜索
        function resetSearch() {
            $('#searchForm')[0].reset();
            loadTrades(1);
            loadStatistics();
        }

        // 刷新表格
        function refreshTable() {
            loadTrades(currentPage);
            loadStatistics();
        }

        // 查看交易详情
        function viewTrade(tradeId) {
            $.get(`/admin/trades/${tradeId}`)
                .done(function(result) {
                    if (result.code === 200) {
                        const trade = result.data;

                        const detailHtml = `
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>交易ID：</strong>${trade.tradeId}</p>
                                    <p><strong>银行卡号：</strong><code>${trade.cardId}</code></p>
                                    <p><strong>交易类型：</strong><span class="badge badge-primary">${trade.tradeType}</span></p>
                                    <p><strong>交易金额：</strong><span class="money-amount">¥${formatMoney(trade.tradeMoney)}</span></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>目标卡号：</strong>${trade.targetCardId ? '<code>' + trade.targetCardId + '</code>' : '无'}</p>
                                    <p><strong>交易时间：</strong>${formatDateTime(trade.tradeDate)}</p>
                                    <p><strong>备注信息：</strong>${trade.remark || '无'}</p>
                                </div>
                            </div>
                        `;

                        showInfoModal('交易详情', detailHtml);
                    } else {
                        showError('获取交易信息失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败');
                });
        }

        // 删除交易记录
        function deleteTrade(tradeId) {
            if (confirm(`确定要删除交易记录"${tradeId}"吗？\n\n注意：删除后将无法恢复！\n\n建议：通常情况下不建议删除交易记录，\n这可能会影响账务的完整性和可追溯性。\n\n如果确实需要删除，请点击"确定"继续。`)) {
                $.ajax({
                    url: `/admin/trades/${tradeId}`,
                    method: 'DELETE'
                })
                .done(function(result) {
                    if (result.code === 200) {
                        showSuccess('交易记录删除成功');
                        loadTrades(currentPage);
                        loadStatistics(); // 重新加载统计信息
                    } else {
                        showError('删除失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('删除请求失败，请稍后重试');
                });
            }
        }

        // 导出交易记录
        function exportTrades() {
            const searchParams = getSearchParams();
            const params = new URLSearchParams();

            if (searchParams.startTime) params.append('startTime', searchParams.startTime);
            if (searchParams.endTime) params.append('endTime', searchParams.endTime);

            const url = '/admin/trades/export' + (params.toString() ? '?' + params.toString() : '');
            window.open(url, '_blank');
        }

        // 导出统计报表
        function exportStatistics() {
            const searchParams = getSearchParams();

            if (!searchParams.startTime || !searchParams.endTime) {
                showError('导出统计报表需要指定时间范围');
                return;
            }

            const params = new URLSearchParams();
            params.append('startTime', searchParams.startTime);
            params.append('endTime', searchParams.endTime);

            const url = '/admin/trades/export-statistics?' + params.toString();
            window.open(url, '_blank');
        }

        // 显示信息模态框
        function showInfoModal(title, content) {
            const modalHtml = `
                <div class="modal fade" id="infoModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">${title}</h5>
                                <button type="button" class="close" data-dismiss="modal">
                                    <span>&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                ${content}
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // 移除已存在的模态框
            $('#infoModal').remove();
            $('body').append(modalHtml);
            $('#infoModal').modal('show');
        }

        // 工具函数
        function formatDateTime(dateTime) {
            if (!dateTime) return '-';
            const date = new Date(dateTime);
            return date.getFullYear() + '-' +
                   String(date.getMonth() + 1).padStart(2, '0') + '-' +
                   String(date.getDate()).padStart(2, '0') + ' ' +
                   String(date.getHours()).padStart(2, '0') + ':' +
                   String(date.getMinutes()).padStart(2, '0') + ':' +
                   String(date.getSeconds()).padStart(2, '0');
        }

        function formatMoney(amount) {
            if (amount == null || amount === '') return '0.00';
            return parseFloat(amount).toFixed(2);
        }

        function showSuccess(message) {
            showAlert('success', message);
        }

        function showError(message) {
            showAlert('danger', message);
        }

        function showAlert(type, message) {
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">
                        <span>&times;</span>
                    </button>
                </div>
            `;

            $('.main-content').prepend(alertHtml);

            setTimeout(function() {
                $('.alert').alert('close');
            }, 3000);
        }
    </script>
</body>
</html>
